const app = getApp()

Page({
  data: {
    activeTab: 0, // 0 for 消息, 1 for 我的
    technicianInfo: null,
    messages: [],
    orderCounts: {
      pending: 0,
      processing: 0,
      completed: 0,
      review: 0
    }
  },

  onLoad() {
    // 初始加载，默认显示消息页面
    this.switchTab({ currentTarget: { dataset: { index: 0 } } });
  },

  onShow() {
    // 页面显示时，重新加载当前tab的数据
    this.checkLoginStatusAndLoadData();
  },

  async checkLoginStatusAndLoadData() {
    let technicianInfo = wx.getStorageSync('technicianInfo');
    // 兼容旧结构
    if (technicianInfo && technicianInfo.technician) {
      technicianInfo = technicianInfo.technician;
      wx.setStorageSync('technicianInfo', technicianInfo); // 立即修正本地缓存
    }
    if (!technicianInfo) {
      app.redirectToTechnicianLogin();
      return;
    }
    this.setData({ technicianInfo });

    if (this.data.activeTab === 0) {
      this.loadMessages();
    } else if (this.data.activeTab === 1) {
      this.loadOrderCounts();
    }
  },

  switchTab(e) {
    console.log('index.js switchTab被调用', e)
    console.log('switchTab时this.data.technicianInfo:', this.data.technicianInfo);
    const index = Number(e.currentTarget.dataset.index);
    this.setData({ activeTab: index });
    if (index === 0) {
      this.loadMessages();
    }
  },

  // from pages/worker/message.js
  async loadMessages() {
    console.log('index.js loadMessages被调用')
    console.log('loadMessages时this.data.technicianInfo:', this.data.technicianInfo);
    console.log('wx.getStorageSync("technicianInfo"):', wx.getStorageSync('technicianInfo'));
    const technicianInfo = this.data.technicianInfo;
    const technicianId = technicianInfo && technicianInfo.id ? technicianInfo.id : undefined;
    if (!technicianId) {
      console.log('technicianInfo为空或没有id，提前return');
      return;
    }
    try {
      const res = await app.request({
        url: '/api/orders',
        method: 'GET'
      });
      console.log('当前工程师ID:', technicianId);
      console.log('后端返回订单:', res.data);
      
      // 获取分配给工程师的订单
      const orders = res.data.filter(item => String(item.technicianId) == String(technicianId));
      console.log('筛选后属于本工程师的订单:', orders);

      // 获取每个订单的最新消息
      const messages = await Promise.all(orders.map(async (order) => {
        try {
          const msgRes = await app.request({
            url: `/api/messages?orderId=${order.id}`,
            method: 'GET'
          });
          
          const latestMessage = msgRes.data && msgRes.data.length > 0 ? 
            msgRes.data[msgRes.data.length - 1] : null;

          return {
            ...order,
            userName: order.userName || '用户' + order.userId,
            userAvatar: order.userAvatar || '/assets/default-avatar.png',
            appointmentTime: (order.appointmentTime || '').replace('T', ' ').slice(0, 16),
            unreadCount: latestMessage && latestMessage.senderId !== technicianId ? 1 : 0,
            lastMessage: latestMessage ? latestMessage.content : '暂无消息'
          };
        } catch (err) {
          console.error(`获取订单 ${order.id} 的消息失败:`, err);
          return {
            ...order,
            userName: order.userName || '用户' + order.userId,
            userAvatar: order.userAvatar || '/assets/default-avatar.png',
            appointmentTime: (order.appointmentTime || '').replace('T', ' ').slice(0, 16),
            unreadCount: 0,
            lastMessage: '获取消息失败'
          };
        }
      }));

      this.setData({ messages });
    } catch (error) {
      console.error('加载消息失败:', error);
      wx.showToast({
        title: '加载消息失败',
        icon: 'none'
      });
    }
  },

  goToOrderDetail(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/worker/orderDetail/orderDetail?id=${orderId}`
    });
  },

  // from pages/worker/center.js
  async loadOrderCounts() {
    const technicianInfo = this.data.technicianInfo;
    if (!technicianInfo || !technicianInfo.id) {
      return;
    }
    try {
      const res = await app.request({
        url: '/api/orders',
        method: 'GET'
      });

      const allOrders = res.data.filter(order => order.technicianId === technicianInfo.id);

      const pending = allOrders.filter(order => order.status === 'CONFIRMED' || order.status === 'PENDING').length;
      const processing = allOrders.filter(order => order.status === 'PROCESSING').length;
      const completed = allOrders.filter(order => order.status === 'COMPLETED').length;

      this.setData({
        'orderCounts.pending': pending,
        'orderCounts.processing': processing,
        'orderCounts.completed': completed
      });

    } catch (error) {
      console.error('加载订单数量失败：', error);
    }
  },

  // 处理订单状态点击事件
  goToOrderList(e) {
    const status = e.currentTarget.dataset.status;
    let statusText = '';
    switch(status) {
      case 'CONFIRMED':
        statusText = '待处理';
        break;
      case 'PROCESSING':
        statusText = '进行中';
        break;
      case 'COMPLETED':
        statusText = '已完成';
        break;
    }
    wx.navigateTo({
      url: `/pages/worker/orderList/orderList?status=${status}&statusText=${statusText}`
    });
  },

  goToMyOrders() {
    // 跳转到订单列表页面，显示全部订单（不传status参数）
    wx.navigateTo({
      url: '/pages/worker/orderList/orderList?status=ALL&statusText=全部订单'
    });
  },

  goToSpecialty() {
    wx.navigateTo({
      url: '/pages/worker/specialty/specialty'
    });
  },

  goToHelp() {
    wx.navigateTo({
      url: '/pages/feedback/feedback'
    });
  },

  goToAbout() {
    wx.navigateTo({
      url: '/pages/about/about'
    });
  },

  logout() {
    console.log('logout方法被调用')
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        console.log('弹窗回调', res)
        if (res.confirm) {
          wx.removeStorageSync('technicianToken');
          wx.removeStorageSync('technicianInfo');
          app.globalData.technicianInfo = null;
          app.redirectToUserMain();
        }
      }
    });
  },

  goToChatDetail(e) {
    const orderId = e.currentTarget.dataset.id;
    const userId = e.currentTarget.dataset.user;
    // 调用后端标记已读接口
    const app = getApp();
    app.request({
      url: `/api/orders/${orderId}/read`,
      method: 'POST'
    });
    // 消除未读红点
    const messages = this.data.messages.map(msg => {
      if (msg.orderId === orderId) {
        return { ...msg, unreadCount: 0 };
      }
      return msg;
    });
    this.setData({ messages });
    wx.navigateTo({
      url: `/pages/worker/chatDetail/chatDetail?orderId=${orderId}&userId=${userId}`
    });
  }
}); 